#!/usr/bin/env python
import logging
import json
import os
import sys
import time
from datetime import datetime, timedelta
import django

# BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
# os.chdir(os.path.join(BASE_DIR, "yijiao_main"))
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
# sys.path.insert(0, os.path.join(BASE_DIR, "pylib"))
# sys.path.insert(0, os.path.join(BASE_DIR, "yijiao_main"))
# django.setup()

from services.datamodel.student.models import mm_Student
from services.asyntask.idle_tasks import queryset_iterator


# logging.basicConfig(
#     level=logging.DEBUG,
#     format="%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s",
#     datefmt="%Y-%m-%d %H:%M:%S",
#     filename=os.path.join("/tmp", "distribute_vip_reward.log")
# )


# Setp three:
# note: Running
# 因为升级，给用户发放7天有效奖励
def distribute_vip_reward():
    result = queryset_iterator(mm_Student.all())
    for qs in result:
        try:
            origin_exp = qs.role_expired_at if qs.role_expired_at else datetime.now()
            role_expired_at = origin_exp + timedelta(days=7)
            mm_Student.filter(id=qs.id).update(role_expired_at=role_expired_at)
        except Exception as e:
            logging.error(e)
        logging.info("successed grant reward with _%s_ of id" % qs.id)
    logging.info("end")


distribute_vip_reward()
# if __name__ == "__main__":
#     start_time = time.time()
#     distribute_vip_reward()
#     print(time.time() - start_time)
